package com.ruoyi.web.controller.meterManager;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.meterManager.domain.Custinfo;
import com.ruoyi.meterManager.domain.MeterPicture;
import com.ruoyi.meterManager.domain.Meterread;
import com.ruoyi.meterManager.domain.requestDto.BaseQueryDto;
import com.ruoyi.meterManager.domain.responseDto.MeterCbHis;
import com.ruoyi.meterManager.domain.responseDto.MeterPayHis;
import com.ruoyi.meterManager.domain.responseDto.UmResponseDto;
import com.ruoyi.meterManager.domain.requestDto.UpdateMrEntity;
import com.ruoyi.meterManager.domain.responseDto.MeterCursor;
import com.ruoyi.meterManager.mapper.MeterreadMapper;
import com.ruoyi.meterManager.service.MeterreadService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 * 
 * @author chenhenan
 */
@RestController
@RequestMapping("/meter")
public class MeterController extends BaseController
{

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MeterreadService meterreadService;
    @Autowired
    private MeterreadMapper meterreadMapper;
    @Autowired
    private ISysUserService userService;
    @Autowired
    HttpServletRequest request;

    @Value("${limitCount}")
    private String limitCount;

    /**
     * 表册信息查询
     * @param baseQueryDto
     * @return
     */
    @GetMapping("/selectBF")
    @RepeatSubmit
    public TableDataInfo selectBF(BaseQueryDto baseQueryDto)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        boolean b = userService.checkUserValidity(loginUser.getUser());
        if(!b){
            throw new CustomException("用户身份认证失败！",HttpStatus.UNAUTHORIZED);
        }
        baseQueryDto.setBfrper(loginUser.getUser().getLoginName());
        List<String> maps = meterreadService.selectBF(baseQueryDto);
        return getDataTable(maps);
    }


    /**
     * 根据条件查询全部、已抄、未抄
     * @param baseQueryDto
     * @return
     */
    @PostMapping("/listMeterread")
    public TableDataInfo list(@RequestBody BaseQueryDto baseQueryDto)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        baseQueryDto.setBfrper(loginUser.getUser().getLoginName());
        String oadept = loginUser.getUser().getDept().getDeptCode();
        String dept = oadept.substring(0, 4);
        baseQueryDto.setDept(dept);
        //如果筛选条件中有余额
        if(StringUtils.isNotBlank(baseQueryDto.getBalance())){
            Map map = meterreadService.selectBaseInfo1(baseQueryDto);
            List<Map> rows = (List<Map>) map.get("rows");
            int counts = (int) map.get("counts");
            return getDataTable2(rows,counts);
            //没有余额/欠费条件
        }else{
            startPage();
            List<Map> maps = meterreadService.selectBaseInfo(baseQueryDto);
            return getDataTable(maps);
        }

    }



    /**
     * 下载全部表计划（离线用）
     * @return
     */
    @GetMapping("/selectDetails")
    @RepeatSubmit
    public TableDataInfo selectAllDetails()
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<MeterCursor> meterCursors = meterreadService.selectDetails(loginUser.getUser().getLoginName());
        if(meterCursors == null || meterCursors.size() == 0){
            //throw new CustomException("查询结果为空");
            return getDataTable1(null, 0,null,null,null);
        }
        SysUser user = userService.selectUserByLoginName(loginUser.getUser().getLoginName());

        String oaname = user.getUserName();
        String oatel = user.getPhonenumber();

        for (MeterCursor m: meterCursors){
            m.setOaname(oaname);
            m.setOatel(oatel);
        }

        return getDataTable1(
                meterCursors,
                meterCursors.size(),
                meterCursors.get(0).getMrmonth(),
                meterCursors.get(0).getTelephone(),
                meterCursors.get(0).getPrintInfo()
        );
    }

    /**
     * 查询表计划详情(单个)
     * @param baseQueryDto
     * @return
     */
    @GetMapping("/selectDetailByMrId")
    //@RepeatSubmit 范说慢7-19
    public AjaxResult selectDetailByMrId(BaseQueryDto baseQueryDto)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        baseQueryDto.setBfrper(loginUser.getUser().getLoginName());
        MeterCursor meterCursor = meterreadService.selectDetailByMrId(baseQueryDto);
        if(meterCursor == null){
            return AjaxResult.success("查询结果为空");
        }
        SysUser user = userService.selectUserByLoginName(loginUser.getUser().getLoginName());
        meterCursor.setOaname(user.getUserName());
        meterCursor.setOatel(user.getPhonenumber());
        return AjaxResult.success(meterCursor);

    }

    /**
     * 手机抄表数据修改
     * @param entity
     * @return
     */
    @PostMapping("/updateMeterCode")
    public AjaxResult updateMeterCode(@RequestPart("file")MultipartFile[] file,
                                      @RequestPart("entity") String entity)
    {
        UpdateMrEntity updateMrEntity = JSON.parseObject(entity,UpdateMrEntity.class);
        LoginUser loginUser = tokenService.getLoginUser(request);
        updateMrEntity.setBfrper(loginUser.getUser().getLoginName());
        UmResponseDto umResponseDto = meterreadService.updateMeter(file,updateMrEntity,loginUser);
        if("222".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"该用户为固定量抄表",umResponseDto);
        }
        if("333".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"已在其它抄表器抄表",umResponseDto);
        }
        /*if("111".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"表态为表异常",umResponseDto);
        }*/
        return AjaxResult.success(umResponseDto);
    }


    /**
     * 查询抄表历史记录
     * @param baseQueryDto
     * @return
     */
    @GetMapping("/selectCbHistory")
    public TableDataInfo selectCbHistory(BaseQueryDto baseQueryDto){
        LoginUser loginUser = tokenService.getLoginUser(request);
        baseQueryDto.setBfrper(loginUser.getUser().getLoginName());
        startPage();
        List<MeterCbHis> meterCbHis = meterreadService.selectCbHistory(baseQueryDto);
        return getDataTable(meterCbHis);
    }

    /**
     * 查询缴费历史记录
     * @param baseQueryDto
     * @return
     */
    @GetMapping("/selectPayHistory")
    public TableDataInfo selectPayHistory(BaseQueryDto baseQueryDto){
        LoginUser loginUser = tokenService.getLoginUser(request);
        baseQueryDto.setBfrper(loginUser.getUser().getLoginName());
        startPage();
        List<MeterPayHis> meterPayHis = meterreadService.selectPayHistory(baseQueryDto);
        return getDataTable(meterPayHis);
    }

    /**
     * 退审接口
     * @param updateMrEntity
     * @return
     */
    @PostMapping("/cancelReview")
    public AjaxResult cancelReview(@RequestBody UpdateMrEntity updateMrEntity){
        String result = meterreadService.cancelReview(updateMrEntity);
        return AjaxResult.success(result);
    }

    /**
     * 获取某总表下分表的抄表状态（如果该总表下有一个分表状态为未抄，则返回false）
     * @param mid
     * @return
     */
    @GetMapping("/getFenStatus")
    public AjaxResult getFenStatus(String mid){
        Boolean result = meterreadService.getFenStatus(mid);
        return AjaxResult.success(result);
    }

    /**
     * 获取本表工所属分公司的强制传照片月份
     * @return
     */
    @GetMapping("/getPictureMonth")
    public AjaxResult getPictureMonth(){
        LoginUser loginUser = tokenService.getLoginUser(request);
        String pictureMonth = meterreadService.getPictureMonth(loginUser.getUser().getLoginName());
        Map data = new HashMap();
        //测试数据
        //pictureMonth = "2,3";
        data.put("month",pictureMonth);
        data.put("num",limitCount);
        return AjaxResult.success("操作成功",data);
    }

    /**
     * 退出登录
     * @param username
     * @return
     */
    @GetMapping("/deleteToken")
    public AjaxResult deleteToken(String username){
        tokenService.delLoginUser(username);
        return AjaxResult.success();
    }

    /**
     * 更新表计划（添加备注）
     * @param meterread
     * @return
     */
    @PostMapping("/updateMeterread")
    public AjaxResult updateMeterread(@RequestBody Meterread meterread){
        return toAjax(meterreadService.updateMeterread(meterread));
    }

    /**
     * 更新客户信息（变更电话）
     * @param custinfo
     * @return
     */
    @PostMapping("/updateCustinfo")
    public AjaxResult updateCustinfo(@RequestBody Custinfo custinfo){
        return toAjax(meterreadService.updateCustinfo(custinfo));
    }



    /**
     * 获取自抄表列表
     * @param query
     * @return
     */
    @GetMapping("/getZcbList")
    @RepeatSubmit
    public TableDataInfo getZcbList(BaseQueryDto query){
        LoginUser loginUser = tokenService.getLoginUser(request);
        query.setBfrper(loginUser.getUser().getLoginName());
        String oadept = loginUser.getUser().getDept().getDeptCode();
        String dept = oadept.substring(0, 4);
        query.setDept(dept);
        startPage();
        List<Map> info = meterreadService.getZcbList(query);
        return getDataTable(info);
    }

    /**
     * 获取自抄表用户详情
     * @param query
     * @return
     */
    @GetMapping("/getZcbDetail")
    public AjaxResult getZcbDetail(BaseQueryDto query){
        LoginUser loginUser = tokenService.getLoginUser(request);
        //String oadept = loginUser.getUser().getDept().getDeptCode();
        query.setBfrper(loginUser.getUser().getLoginName());
        Map info = meterreadService.getZcbDetail(query);
        return AjaxResult.success(info);
    }

    /**
     * 自抄表审核拒绝原因
     * @return
     */
    @GetMapping("/getZcbRefuseReason")
    public AjaxResult getZcbRefuseReason(){
        List<Map> reasons = meterreadService.getZcbRefuseReasonList();
        return AjaxResult.success(reasons);
    }

    /**
     * 自抄表审核
     * @param meterPicture
     * @return
     */
    @PostMapping("/checkZcb")
    public AjaxResult checkZcb(@RequestBody MeterPicture meterPicture){
        meterreadService.checkZcb(meterPicture);
        return AjaxResult.success();
    }


    /**
     * 自抄表审核并行接口
     * @param meterPicture
     * @return
     */
    @PostMapping("/checkZcbParallel")
    public AjaxResult checkZcbParallel(@RequestBody MeterPicture meterPicture){
        meterreadService.checkZcb(meterPicture);
        return AjaxResult.success();
    }

    /**
     * 手机抄表并行接口
     * @param entity
     * @return
     */
    @PostMapping("/updateMeterParallel")
    public AjaxResult updateMeterParallel(@RequestPart("file")MultipartFile[] file,
                                          @RequestPart("entity") String entity)
    {
        UpdateMrEntity updateMrEntity = JSON.parseObject(entity,UpdateMrEntity.class);
        //LoginUser loginUser = tokenService.getLoginUser(request);
        LoginUser loginUser = new LoginUser();
        SysUser user = new SysUser();
        user.setLoginName(updateMrEntity.getBfrper());
        user.setUserName(updateMrEntity.getOaname());
        loginUser.setUser(user);
        //updateMrEntity.setBfrper(loginUser.getUser().getLoginName());
        UmResponseDto umResponseDto = meterreadService.updateMeter(file,updateMrEntity,loginUser);
        if("222".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"该用户为固定量抄表",umResponseDto);
        }
        if("333".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"已在其它抄表器抄表",umResponseDto);
        }
        /*if("111".equals(umResponseDto.getCode())){
            return AjaxResult.success(Integer.parseInt(umResponseDto.getCode()),"表态为表异常",umResponseDto);
        }*/
        return AjaxResult.success(umResponseDto);
    }






}
